<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态执行JS</title>
</head>
<body>
    <script>
        let a= 1;
        // eval:同步，当前作用域
        function exec1(code){
            let a= 2;
            eval(code)
        }
        // setTimeout:异步，全局作用域
        function exec2(code){
            let a= 2;
            setTimeout(code)
        }
        // script:同步，全局作用域
        function exec3(code){
            let a= 2;
            const script = document.createElement("script");
            script.text = code;
            document.head.appendChild(script);
        }
        // Function:同步，全局作用域
        function exec4(code){
            let a= 2;
            new Function(code)();
        }
        exec1('console.log("exec1",a)');
        exec2('console.log("exec2",a)');
        exec3('console.log("exec3",a)');
        exec4('console.log("exec4",a)');
        console.log('sync')
    </script>
</body>
</html>